package com.example.testapp.activity.activity.study;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.testapp.R;
import com.example.testapp.activity.fragment.AboutMeFragment;
import com.example.testapp.activity.fragment.ChangeBackgroundFragment;
import com.example.testapp.activity.fragment.CityManagerFragment;
import com.example.testapp.activity.fragment.FragmentAnd;
import com.example.testapp.activity.fragment.HomePageFragment;
import com.example.testapp.activity.fragment.LifeIndexFragment;
import com.example.testapp.activity.http.HttpUtil;
import com.example.testapp.activity.http.MHttpEntity;
import com.example.testapp.activity.model.CityManagerEntity;
import com.example.testapp.activity.model.ResponseWrapper;
import com.example.testapp.activity.model.SendDataEntity;
import com.example.testapp.activity.util.SharePreferenceUtil;
import com.example.testapp.activity.util.SystemUtils;
import com.google.gson.GsonBuilder;

import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by l on 2016/8/1.
 */
public class WeaterMainActivity extends AppCompatActivity implements FragmentAnd, View.OnClickListener{

    public static ResponseWrapper response = new ResponseWrapper();
    public static ResponseWrapper response2;

    public boolean netErrorFlag=false;

    private EditText inputcity;
    private DrawerLayout mDrawerLayout = null;
    private View   mLeftBtn;
    private Button   mRefreshBtn = null;
    public static final int succeed = 1;
    public static final int fail = 2;
    public static final int nonet = 3;
    private static int tag = 0;
    private long nowtime;
    public static String TAG_H = null;
    private ProgressDialog Dialog;
    public static HomePageFragment homecontent = new HomePageFragment();
    public CityManagerFragment citymanager = new CityManagerFragment();
    public static CityManagerEntity cmb2 = new CityManagerEntity();
    private ChangeBgReceiver mReceiver;

    private class ChangeBgReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            String path = intent.getStringExtra("path");
            if(path == null){
                Log.i("weather", "path is null");
            }else{
                Log.i("weather", path);
            }
            boolean auto =  intent.getBooleanExtra("auto", false);
            Bitmap bitmap = getBitmapPath(path, auto);
            if(bitmap != null){
                mDrawerLayout.setBackgroundDrawable(new BitmapDrawable(getResources(), bitmap));
            }
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);

        initData();
        initBroadCast();
        initView();
    }

    private void initData() {
        Intent intent = getIntent();
        String wetherdata = intent.getStringExtra("weather_data");
        GsonBuilder gson = new GsonBuilder();
        response2 = gson.create().fromJson(wetherdata, ResponseWrapper.class);
        if(response2 != null){
            if(response2.getError() == 0){
                response = response2;
            }
        }else{
             netErrorFlag = true;
        }
    }

    private void initView() {
        mDrawerLayout = (DrawerLayout)findViewById(R.id.drawerlayout_main);
        initBgPic();
        mLeftBtn = findViewById(R.id.left_drawer);
        mDrawerLayout.setScrimColor(0x00000000);
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft =fm.beginTransaction();
        ft.replace(R.id.fragmentlayout, homecontent, HomePageFragment.TAG);
        ft.commit();
    }

    private void initBgPic() {
        String path = new SharePreferenceUtil(this).getPath();
        Intent intent = new Intent("change_background");
        intent.putExtra("path", path);
        sendBroadcast(intent);
    }

    private void initBroadCast() {
        mReceiver = new ChangeBgReceiver();
        IntentFilter filter = new IntentFilter("change_background");
        registerReceiver(mReceiver, filter);
    }

    private Bitmap getBitmapPath(String path, boolean auto) {
        AssetManager  am = this.getAssets();
        Bitmap bitmap = null;
        InputStream is = null;
        try{
            if(auto == false){
                is = am.open("bkgs/" + path);
            }else if(auto == true){
                Log.i("weather", "before open auto_bkgs");
                is = am.open("autobkgs/" + path);
                Log.i("weather", path);
            }
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        }catch (IOException e){
            e.printStackTrace();
            Log.i("weather", "open file error");
        }
        return bitmap;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

    @Override
    public void senddata(EditText inputcity) {
          this.inputcity = inputcity;
    }

    @Override
    public void sendcitytext(final String inputcitytext) {
        tag = 4;
        if(" ".equals(inputcitytext)){
           showToast(getString(R.string.action_edit));
           if(HomePageFragment.Dialog != null){
               HomePageFragment.Dialog.dismiss();
           }
        }else {
           SendDataEntity.setCity(inputcitytext); // 获取用户输入城市
           new Thread(new Runnable() {
               @Override
               public void run() {
                   try {
                       Thread.sleep(1000);
                       sendRequest(inputcitytext);
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
               }
           }).start();
        }
    }

    @Override
    public void showDialog() {
        Dialog = new ProgressDialog(WeaterMainActivity.this);
        Dialog.setCancelable(true);
        Dialog.setCancelable(true);
        Dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        Dialog.setMessage("正在更新...");
        Dialog.show();
    }

    /**
     * 连续按两次返回则退出程序
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            if(System.currentTimeMillis() - nowtime > 2000){
                Toast.makeText(this, R.string.click_exit, Toast.LENGTH_SHORT).show();
                nowtime = System.currentTimeMillis();
                return true;
            }else{
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.homep_menu:
                switchLeftLayout();
                break;
            case R.id.homep_refresh:
                if(HttpUtil.isNetWorkConnect(getApplicationContext())){
                    refresh();
                }else{
                    Toast.makeText(getApplicationContext(), "网络未连接，请检查网络设置", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_life:
                switchLeftLayout();
                switchFragment(new LifeIndexFragment(),null);
                break;
            case R.id.btn_city_manager:
                switchLeftLayout();
                switchFragment(citymanager, null);
                break;
            case R.id.btn_change_bag:
                switchLeftLayout();
                switchFragment(new ChangeBackgroundFragment(), null);
                break;
            case R.id.btn_about:
                switchLeftLayout();
                switchFragment(new AboutMeFragment(), null);
                break;
            case R.id.btn_share_app:
                SystemUtils.shareApp(this);
                break;
            case R.id.exitapp:
                showExitDialog();
                break;
        }
    }

    private void showExitDialog() {
        final Dialog dialog = new Dialog(this, android.R.style.Theme_DeviceDefault_Dialog_NoActionBar);
        View  exitappview = getLayoutInflater().inflate(R.layout.view_city_dialog, null);
        TextView  exitapp = (TextView) exitappview.findViewById(R.id.exitapp_text);
        Button  leftBtn = (Button)exitappview.findViewById(R.id.leftbutton);
        Button  rightBtn = (Button)exitappview.findViewById(R.id.rightbutton);
        exitapp.setText("退出程序");
        leftBtn.setText("确定");
        rightBtn.setText("取消");
        leftBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        rightBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setContentView(exitappview);
        dialog.show();
    }

    /**
     * 关联menu键
     */
    private void switchLeftLayout() {
        if(mDrawerLayout.isDrawerOpen(mLeftBtn)){
            mDrawerLayout.closeDrawer(mLeftBtn);
        }else{
            mDrawerLayout.openDrawer(mLeftBtn);
        }
    }

    private void refresh() {
        showDialog();
        switchFragment(homecontent, null);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    sendRequest(HomePageFragment.currentcity.getText().toString());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void switchFragment(Fragment fragment, String str) {
       FragmentManager fm = getSupportFragmentManager();
       FragmentTransaction ft = fm.beginTransaction();
       ft.replace(R.id.fragmentlayout, fragment, null);
       ft.commit();
    }

    /**
     * 向服务器发送数据请求
     */
    private void sendRequest(String cityname) {
        String getData = null;
        MHttpEntity mhe = null;
        try {
            SendDataEntity.setCity(cityname); // 获取用户输入的城市名
            mhe = MHttpEntity.sendHttpRequest(SendDataEntity.getData());
            if(mhe.getHentity() != null){
                getData = EntityUtils.toString(mhe.getHentity());
                mhe.getMessage().obj = getData;
            }
        }catch (ParseException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        handler.sendMessage(mhe.getMessage());// 使用Handler对网络状态做处理
    }

    public Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(Dialog != null)
                Dialog.dismiss();
            if(msg != null)
                switch (msg.arg1){
                    case succeed: // 与服务器连接成功
                         if(msg.obj != null) {
                             fromIson(msg.obj.toString());
                         }
                             break;
                    case fail: // 与服务器连接失败
                        showToast(getString(R.string.net_fail));
                        break;
                }
        }
    };

    private void fromIson(String wetherdata) {
        GsonBuilder gson = new GsonBuilder();
        response2 = gson.create().fromJson(wetherdata, ResponseWrapper.class);
        if(response2.getError() == 0){
            response = response2;
            homecontent.setpagedata();
            if(tag == 4 && inputcity != null){
                closeinput(inputcity);
            }
        }else if(response2.getError() == -3 || response2.getError() == -2){
            showToast(getString(R.string.input_truename));
        }else{
            showToast(getString(R.string.getdata_fail));
        }
        if(HomePageFragment.Dialog != null){
            HomePageFragment.Dialog.dismiss();
        }
    }

    /**
     * 关闭输入法键盘
     */
    private void closeinput(EditText editText) {
        editText.setText(" ");
        InputMethodManager manager = (InputMethodManager) getSystemService(WeaterMainActivity.INPUT_METHOD_SERVICE);
        manager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }

    /**
     * 点击多次bt，Toast只显示一次的解决方案
     */
    public Toast toast = null;

    public void showToast(String text) {
        if(toast == null){
            toast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
        }else{
            toast.setText(text);
        }
        toast.show();
    }
}
